<?php
/**
 * Author: top-songshijie
 * DateTime: 2020/03/20 23:38
 */

namespace SwoPhp\Server;

use Swoole\Server as SwooleServer;

abstract class Server
{
    protected $host = '0.0.0.0';

    protected $port = '9501';

    protected $swooleServer;

    protected $event = [
        'server' => [
            'start'        => 'onStart',
            'managerStart' => 'onManagerStart',
            'managerStop'  => 'onManagerStop',
            'shutdown'     => 'onShutdown',
            'workerStart'  => 'onWorkerStart',
            'workerStop'   => 'onWorkerStop',
            'workerError'  => 'onWorkerError',
        ],
        'sub'    => [],
        'ext'    => []
    ];

    protected $config = [
        'task_worker_num' => 0
    ];

    public function __construct()
    {
        $this->initSetting();
        $this->createServer();
        $this->initEvent();
        $this->setSwooleEvent();

    }

    public function start()
    {
        $this->swooleServer->start();
    }

    protected abstract function initSetting();

    protected abstract function createServer();

    protected abstract function initEvent();

    public function setSwooleEvent()
    {
        foreach ($this->event as $type => $events) {
            foreach ($events as $event => $func) {
                $this->swooleServer->on($event, [$this, $func]);
            }
        }
    }

    public function setEvent($type, $event)
    {
        $this->event[$type] = $event;
        return $this;
    }

    public function setConfig($config)
    {
        $this->config = array_map($this->config, $config);
        return $this;
    }

    public function onStart(SwooleServer $server)
    {

    }

    public function onManagerStart(SwooleServer $server)
    {

    }

    public function onManagerStop(SwooleServer $server)
    {

    }

    public function onShutdown(SwooleServer $server)
    {

    }

    public function onWorkerStart(SwooleServer $server, int $worker_id)
    {

    }

    public function onWorkerStop(SwooleServer $server, int $worker_id)
    {

    }

    public function onWorkerError(SwooleServer $server, int $workerId, int $workerPid, int $exitCode, int $signal)
    {
    }

}
